#!/bin/sh
# PCP QA Test No. 1232
# pmlogger_daily -k 0 tests
#
# Copyright (c) 2020 Ken McDonell.  All Rights Reserved.
#

seq=`basename $0`
echo "QA output created by $seq"

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

if pmlogctl -c default status 2>/dev/null | grep ' default ' >/dev/null
then
    _notrun "at least one pmlogger already defined for \"default\" class"
fi

NEEDREWRITE=$PCP_LOG_DIR/pmlogger/.NeedRewrite

_cleanup()
{
    echo "_cleanup: ..." >>$seq.full
    cd $here
    $sudo pmlogctl -f -c default destroy localhost >>$seq.full 2>&1
    $sudo rm -rf $tmp $tmp.*
    $sudo rm -rf $PCP_ARCHIVE_DIR/localhost
    [ -f $NEEDREWRITE.$seq ] && $sudo mv $NEEDREWRITE.$seq $NEEDREWRITE

}

status=1	# failure is the default!
$sudo rm -rf $tmp $tmp.* $seq.full
trap "_cleanup; exit \$status" 0 1 2 3 15

[ -f $NEEDREWRITE ] && $sudo mv $NEEDREWRITE $NEEDREWRITE.$seq

_filter()
{
    tee -a $seq.full \
    | sed \
	-e '/^# created by pmlogctl/s/ on .*/ on DATE/' \
	-e "s;$tmp\.;TMP.;g" \
	-e "s;$PCP_BINADM_DIR/;PCP_BINADM_DIR/;g" \
	-e "s;$PCP_ARCHIVE_DIR/;PCP_ARCHIVE_DIR/;g" \
	-e "s;$PCP_TMP_DIR/;PCP_TMP_DIR/;g" \
	-e "s;$PCP_TMPFILE_DIR/pmlogctl\.[^/]*;PCP_TMPFILE_DIR/pmlogctl.XXXXX;g" \
	-e "s;$PCP_ETC_DIR/;PCP_ETC_DIR/;g" \
    # end
}

_filter_log()
{
    cat \
    | _filter \
    | sed \
	-e '1,/=== daily /d' \
	-e '/^Start:/d' \
	-e '/^End:/d' \
	-e '/^COMPRESSAFTER=/d' \
	-e '/^\+ /d' \
	-e '/^\.\.\. try /d' \
	-e '/^\.\.\. logging for /d' \
	-e '/no pmlogger instance running /d' \
	-e '/skipping log rotation/d' \
	-e '/[0-9][0-9]* identified/s//PID identified/' \
	-e '/current [0-9][0-9.-]* archive/s//current DATE archive/' \
	-e 's/ [0-9][0-9.-]*.index/ DATE.index/g' \
	-e 's/ [0-9][0-9.-]*.meta/ DATE.meta/g' \
	-e 's/ [0-9][0-9.-]*.0/ DATE.0/g' \
	-e '/ DATE/{
s/\.xz//g
s/\.lzma//g
s/\.bz2//g
s/\.bz//g
s/\.gz//g
s/\.Z//g
s/\.z//g
}'
    # done
}

# get our pmlogger running
#
$sudo pmlogctl -V create localhost | _filter

# real QA test starts here
control=$PCP_ETC_DIR/pcp/pmlogger/control.d/localhost

echo
echo "only one current archive, expect no culling"
$sudo -u $PCP_USER -g $PCP_GROUP $PCP_BINADM_DIR/pmlogger_daily -c $control \
    -N -VV -k 0 -x never 2>&1 \
| _filter_log

echo
echo "one archive, cull it"
$sudo pmlogctl stop localhost
$sudo -u $PCP_USER -g $PCP_GROUP $PCP_BINADM_DIR/pmlogger_daily -c $control \
    -N -VV -k 0 -x never 2>&1 \
| _filter_log

echo
echo "cull old archive, skip current one"
$sudo pmlogctl start localhost
$sudo -u $PCP_USER -g $PCP_GROUP $PCP_BINADM_DIR/pmlogger_daily -c $control \
    -N -VV -k 0 -x never 2>&1 \
| _filter_log

echo
echo "two archives, cull 'em"
$sudo pmlogctl stop localhost
$sudo -u $PCP_USER -g $PCP_GROUP $PCP_BINADM_DIR/pmlogger_daily -c $control \
    -N -VV -k 0 -x never 2>&1 \
| _filter_log

# success, all done
status=0
exit
